package com.dxhackday.ppicker;

import javafx.animation.*;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.control.Label;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.util.Duration;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

/**
 * @author Sergey Lyadzhin
 * @since 24.11.12 14:12
 */
public class CountdownController implements Initializable {
    private static final Integer COUNTDOWN = 5;

    @FXML private Label countdownLabel;
    private IntegerProperty countdown = new SimpleIntegerProperty();
    private Animation countdownAnimation;

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        countdownLabel.textProperty().bind(countdown.asString());

        countdown.set(COUNTDOWN);

        countdownAnimation = new ParallelTransition(new Timeline(new KeyFrame(Duration.seconds(1), new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                int value = countdown.get();
                countdown.set(value - 1);
            }
        })),
                FadeTransitionBuilder.create().node(countdownLabel).duration(Duration.seconds(1)).fromValue(1.0f).toValue(0.0f).build()
        );
        countdownAnimation.setCycleCount(COUNTDOWN);
        countdownAnimation.setOnFinished(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                if (countdownAnimation != actionEvent.getSource())
                    return;
                gotoPlayback();
            }
        });
        countdownAnimation.playFromStart();
    }

    public void handleKeyPressed(KeyEvent event) {
        stopCountdown();
    }

    private void stopCountdown() {
        countdownAnimation.stop(); // onFinished() is not called after stop
        gotoPlayback();
    }

    public void handleMouseClicked(MouseEvent event) {
        stopCountdown();
    }

    private void gotoPlayback()  {
        Parent newRoot = null;
        try {
            newRoot = FXMLLoader.load(PhotoPickerApplication.class.getResource("playback.fxml"));
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        countdownLabel.getScene().setRoot(newRoot);
    }

}
